package cn.tedu.egmvcboot.controller;

import cn.tedu.egmvcboot.mapper.UserMapper;
import cn.tedu.egmvcboot.pojo.dto.UserArticleDTO;
import cn.tedu.egmvcboot.pojo.dto.UserLoginDTO;
import cn.tedu.egmvcboot.pojo.entity.Article;
import cn.tedu.egmvcboot.pojo.entity.User;
import cn.tedu.egmvcboot.common.result.JsonResult;
import cn.tedu.egmvcboot.common.result.Status;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import javax.servlet.http.HttpSession;

@Slf4j
@RestController
@RequestMapping("/v2/users")
@Api(tags = "用户模块")
@Validated
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public JsonResult login(@RequestBody @Validated UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        System.out.println("用户登录信息："+userLoginDTO);
        User User=userMapper.selectUser(userLoginDTO.getUsername(),userLoginDTO.getPassword());
        if (User!=null){
            session.setAttribute("user",User);
            return JsonResult.success(User);
        }else {
            return new JsonResult(Status.USERNAME_PASSWORD_ERROR);
        }
//        userMapper.selectUser(UserVO);
    }
    @ApiOperation("发表文章")
    @PostMapping("/article")
    public JsonResult addArticle(@RequestBody @Validated UserArticleDTO userArticleDTO,@ApiIgnore HttpSession session){
        System.out.println("发表文章信息："+userArticleDTO);
        User user=(User)session.getAttribute("user");
        if (user==null){
            return new JsonResult(Status.NOT_LOGIN);
        }
        Article article=new Article();
//        article.setTitle(userArticleDTO.getTitle());
//        article.setContent(userArticleDTO.getContent());
        BeanUtils.copyProperties(userArticleDTO,article);
        article.setUserId(user.getId());
        userMapper.insert(article);
        return JsonResult.success("发表文章成功");
    }
    @ApiOperation("查询文章")
    @GetMapping("/selectByArticleId")
    @ApiImplicitParam(name = "id",value = "文章ID",required = true,example = "1",dataType = "int")
    public JsonResult selectByArticleId(@RequestParam@Range(min = 1,max = 100,message = "id只能在1-100之间")Integer id){
        System.out.println("id="+id);
        return JsonResult.success(userMapper.selectArticleById(id));
    }
}
